<template>
  <TableView class="role">
    <template #form>
      <NSpace justify="space-between">
        <NForm
          :show-feedback="false"
          label-placement="left"
          inline
        >
          <span style="line-height: 34px">文润志愿服务联盟：</span>
          <NSelect
            :options="listOption"
            v-model:value="form.leagueId"
            placeholder="选择联盟"
            clearable
            style="width: 150px; margin-right: 20px"
            :render-option="renderOption"
          />
          <NFormItem>
            <NButton
              type="primary"
              style="width: 78px"
              ghost
              @click="queryTableData(true)"
              :loading="tableLoading"
            >
              查询
            </NButton>
          </NFormItem>
          <NFormItem>
            <NButton
              ghost
              type="primary"
              @click="resetForm"
              style="width: 78px;margin-left: 20px;"
            >
              重置
            </NButton>
          </NFormItem>
          
        </NForm>
        <NSpace align="end">
          <NButton
            type="primary"
            style="width: 115px"
            @click="handleAdd"
          >
            配置
          </NButton>
        </NSpace>
      </NSpace>
    </template>
    <template #table="props">
      <n-data-table
        v-bind="props"
        :data="tableData"
        :columns="columns"
        :loading="tableLoading"
        size="small"
        :bordered="false"
        :rowKey="rowKey"
        :checked-row-keys="rowKeys"
      />
    </template>
    <template #pagination>
      <NPagination
        show-size-picker
        show-quick-jumper
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
      >
        <template #suffix>页</template>
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent
      @close="modalVisible = false"
      @submit="againDelete"
      title="清除提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要清除吗?
      </div>
    </VDialogContent>
  </NModal>
  <NModal :auto-focus="false" v-model:show="modalAdd">
    <VDialogContent
      @close="cancel"
      @submit="confirm"
      :title="title"
    >
      <div style="width: 500rem; height: 260rem; text-align: center; line-height: 100rem">
        <NSpace justify="center">
          <NForm
            ref="formRef"
            require-mark-placement="left"
            label-placement="left"
            :rules="rules"
            :label-width="120"
            :model="formValue"
            label-align="left"
          >
            <!-- <NSpace>
              <NFormItem
                label="签到时间:"
                path="startConfigDate"
              >
               <NDatePicker input-readonly
                  placeholder="请选择签到时间"
                  class="commonWidth"
                  clearable
                  format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"  default-time="00:00:00"
                  v-model:formatted-value="formValue.startConfigDate"
                />
              </NFormItem>
            </NSpace>
            <NSpace>
              <NFormItem
                label="签出时间:"
                path="endConfigDate"
              >
               <NDatePicker input-readonly
                  placeholder="请选择签出时间"
                  class="commonWidth"
                  clearable
                  format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"  default-time="00:00:00"
                  v-model:formatted-value="formValue.endConfigDate"
                />
              </NFormItem>
            </NSpace> -->
            <NSpace>
              <NFormItem
                label="上班最多可晚到:"
                path="arriveLate"
              >
                <NSelect
                  :options="minOption"
                  v-model:value="formValue.arriveLate"
                  placeholder="请选择"
                  clearable
                  style="width: 150px;"
                />
              </NFormItem>
            </NSpace>
            <NSpace>
              <NFormItem
                label="下班最多可早走:"
                path="leaveEarly"
              >
                <NSelect
                  :options="minOption"
                  v-model:value="formValue.leaveEarly"
                  placeholder="请选择"
                  clearable
                  style="width: 150px;"
                />
              </NFormItem>
            </NSpace>
          </NForm>
        </NSpace>
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import {
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NModal,
  NForm,
  NFormItem,
  NSelect,
  NPopconfirm,
  NTag,
  NDatePicker,
  NTooltip
} from 'naive-ui'
import { onActivated, onMounted, reactive, ref, h ,watch} from 'vue'
import { sendRequest } from '@/utils/api'
import type { signConfigModel } from '@/api/volunteer'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute, useRouter } from 'vue-router'

const message = useMessage()
const router = useRouter()

onActivated(() => {
  if (window.flags.flushRole) {
    queryTableData(true)
    window.flags.flushRole = false
  }
})

const  renderOption = ({ node, option }: { node: VNode; option: SelectOption }) =>
  h(NTooltip, null, {
    trigger: () => node,
    default: () => option.label
  })

const tableData = ref<signConfigModel[]>([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
type Reset = () => void
function useQueryForm<T = unknown>(form: T, reset: Reset): [form: T, reset: Reset] {
  return [form, reset]
}
const modalVisible = ref(false)
const modalAdd = ref(false)
const route = useRoute()
const title = ref('志愿服务联盟新增');
const [form, resetForm] = useQueryForm(
  reactive({
    leagueId: null,
  }),
  () => {
    form.leagueId = null
  }
)
const formValue = reactive({
  endConfigDate: null,
  startConfigDate: null,
  arriveLate: '',
  leaveEarly: '',
  leagueId: '',
  id: ''
})
const minOption = ref([
  {
    label: '1分钟',
    value: 1
  },
  {
    label: '2分钟',
    value: 2
  },
  {
    label: '3分钟',
    value: 3
  },
  {
    label: '4分钟',
    value: 4
  },
  {
    label: '5分钟',
    value: 5
  },
  {
    label: '6分钟',
    value: 6
  },
  {
    label: '7分钟',
    value: 7
  },
  {
    label: '8分钟',
    value: 8
  },
  {
    label: '9分钟',
    value: 9
  },
  {
    label: '10分钟',
    value: 10
  }
])

const formRef = ref<FormInst | null>(null)


const rules = {
  // arriveLate: {
  //   required: true,
  //   message: '请选择上班最多可晚到',
  //   trigger: ['change', 'blur']
  // },
  // leaveEarly: {
  //   required: true,
  //   message: '请选择下班最多可早走',
  //   trigger: ['change', 'blur']
  // },
}

const listOption = ref([]);
const rowKey: any = (row: any) => row.id || ''

const columns: DataTableColumns<signConfigModel> = [
  // {
  //   type: 'selection',
  //   fixed: 'left',
  //   width: '2rem'
  // },
  {
    title: '文润志愿服务联盟',
    key: 'leagueName',
    width: '10rem',
    align: 'center'
  },
  // {
  //   title: '签到时间',
  //   key: 'startConfigDate',
  //   width: '10rem',
  //   align: 'center',
  // },
  // {
  //   title: '签出时间',
  //   key: 'endConfigDate',
  //   width: '10rem',
  //   align: 'center',
  // },
  {
    title: '晚到',
    key: 'arriveLate',
    width: '10rem',
    align: 'center',
    render: (row: any) => {
      return h(
        NTag,
        {
          style: {
            marginRight: '6px'
          },
          type: 'info',
          bordered: false
        },
        {
          default: () => `${row.arriveLate}分钟`
        }
      )
    }
  },
  {
    title: '早退',
    key: 'leaveEarly',
    width: '10rem',
    align: 'center',
    render: (row: any) => {
      return h(
        NTag,
        {
          style: {
            marginRight: '6px'
          },
          type: 'info',
          bordered: false
        },
        {
          default: () => `${row.leaveEarly}分钟`
        }
      )
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '20rem',
    align: 'center',
    fixed: 'right',
    render: (row: any) => {
      let name = '';
      row.listFlag == 1 ? name = '下架' : name = '上架'
      return [
        h(
          NButton,
          {
            type: 'primary',
            quaternary: true,
            onClick: () => handleEdit(row)
          },
          {
            default: () => '编辑'
          }
        ),
        h(
          NButton,
          {
            type: 'error',
            quaternary: true,
            onClick: () => handleDelete(row.id)
          },
          {
            default: () => '清除'
          }
        )
        // h(
        //   NPopconfirm,
        //   {
        //     positiveButtonProps: {
        //       size: 'tiny',
        //       color: '#007293',
        //       bordered: true,
        //     },
        //     negativeButtonProps: {
        //       size: 'tiny',
        //       color: '#007293',
        //       bordered: true,
        //     },
        //     onPositiveClick: (e: any) => {
        //       handleDelete(row.id)
        //     }
        //   },
        //   {
        //     trigger: () => {
        //       return h(
        //         NButton,
        //         {
        //           type: 'error',
        //           quaternary: true,
        //         },
        //         { default: () => '清除' }
        //       )
        //     },
        //     default: () => {
        //       return '确认清除吗？'
        //     }
        //   }
        // ),
      ]
    }
  }
]
const type = ref('');
const tableLoading = ref(false)
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<signConfigModel>>({
    module: 'volunteer',
    api: 'signConfigList',
    override: {
      params: {
        leagueId: form.leagueId,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value = res.data.list
}

const handleEdit = (e: any) => {
  title.value = '志愿者签到配置编辑';
  type.value = 'edit';
  formValue.startConfigDate = e.startConfigDate;
  formValue.endConfigDate = e.endConfigDate;
  formValue.leaveEarly = e.leaveEarly;
  formValue.arriveLate = e.arriveLate;
  formValue.id = e.id;
  formValue.leagueId = e.leagueId;
  modalAdd.value = true;
}

const handleAdd = () => {
  type.value = 'add';
  title.value = '志愿者签到配置';
  modalAdd.value = true;
}

const ids = ref()

const handleDelete = async (id: any) => {
  ids.value = id
  modalVisible.value = true
  // const [error] = await sendRequest<HttpResponse>({
  //   module: 'volunteer',
  //   api: 'signConfigDelete',
  //   override: {
  //     data: [id]
  //   }
  // })
  // if (error) return message.error(error.message)
  // message.success('清除成功')
  // queryTableData()
}

const againDelete = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'volunteer',
    api: 'signConfigDelete',
    override: {
      data: [ids.value]
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) {
    message.error(res.msg)
  } else {
    message.success('清除成功')
    queryTableData(true)
    modalVisible.value = false
  }
}

const cancel = () => {
  formValue.startConfigDate = null;
  formValue.endConfigDate = null;
  formValue.leaveEarly = '';
  formValue.arriveLate = '';
  formValue.id = '';
  formValue.leagueId = '';
  modalAdd.value = false;
}

const confirm = async() => {
  console.log('formValue.id', formValue.id)
  console.log('formValue', formValue)
  let params:any = {
    ...formValue
  }
  if (!params.leaveEarly) {
    params.leaveEarly = 0;
  }
  if (!params.arriveLate) {
    params.arriveLate = 0;
  }
  if (type.value == 'edit') {
    formRef.value?.validate(async (error:any) => {
      if (error) return
      try {
        const [error] = await sendRequest<HttpResponse>({
          module: 'volunteer',
          api: 'signConfigUpdate',
          override: {
            data: params
          }
        })
        if (error) return message.error(error.message)
        queryTableData(true)
        modalAdd.value = false
      } catch (error: any) {
        message.error(error.message)
      }
    })
  } else {
    formRef.value?.validate(async (error:any) => {
      if (error) return
      try {
        const [error] = await sendRequest<HttpResponse>({
          module: 'volunteer',
          api: 'signConfigSave',
          override: {
            data: {
              startConfigDate: formValue.startConfigDate,
              endConfigDate: formValue.endConfigDate,
              leaveEarly: formValue.leaveEarly || 0,
              arriveLate: formValue.arriveLate || 0,
            }
          }
        })
        if (error) return message.error(error.message)
        queryTableData(true)
        modalAdd.value = false
      } catch (error: any) {
        message.error(error.message)
      }
    })
  }
}
//下拉
const getFunction = async () => {
  listOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'volunteer',
    api: 'leagueOptions'
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listOption.value.push({ label: i.label, value: i.value })
  })
}

onMounted(() => {
  getFunction()
  queryTableData(true)
})
watch(
  () => route,
  () => {
    if (
      route.path == '/collectionManagement/collectionProcess/clueManagement/index'
    ) {
      queryTableData(true)
    }
  },
  { deep: true, immediate: true }
)
</script>

<style lang="scss" scoped>
.role {
  padding: 29rem 20rem 42rem 30rem;
  color: rgba(0, 0, 0, 0.85);
}
</style>
